import { ApiRequest } from '@api/basePage'
import { cityTreeDataUtils } from '@/assets/js/commonUtils'
const state = {
  areaSelectedList: [], // 已选择区域（省份）对象集合
  selectedAreaListStr: {}, // 已选区域（省份）名字、code拼接字符串组成的对象
  treeAreaData: [], // 请求到的当前模态框的区域（省份）列表
}

const mutations = {
  /* 设置当前已选区域（省份）集合 */
  SET_SELECTED_AREA_LIST: (state, data) => {
    let appliedArea = ''
    let appliedAreaName = ''
    if (data.length === 0) {
      state.areaSelectedList = []
      appliedArea = ''
      appliedAreaName = ''
    } else {
      data.forEach(item => {
        if (item.children === undefined) {
          appliedArea += item.code + ',';
          appliedAreaName += item.title + ',';
          state.areaSelectedList.push({
            code: item.code,
            title: item.title,
            uuid: item.uuid
          })
        }
      })
    }
    appliedArea = appliedArea.slice(0, appliedArea.length - 1)
    appliedAreaName = appliedAreaName.slice(0, appliedAreaName.length - 1)
    state.selectedAreaListStr = {
      appliedArea,
      appliedAreaName
    }
  },
  /* 设置区域（省份）列表 */
  SET_AREA_TREE: (state, data) => {
    let dataList = cityTreeDataUtils(data)
    let treeCitiesList = dataList.reduce((value, item) => {
      let { checked, code, expand, nodeKey, position, title } = item
      value.push({
        checked,
        code,
        expand,
        nodeKey,
        position,
        title
      })
      return value
    }, [])
    state.treeAreaData = [
      {
        title: '全选',
        expand: true,
        checked: false,
        children: treeCitiesList
      }
    ]
  },
  /* 改变区域（省份）列表的checked */
  CHANGE_AREA_CHECKED: (state, data) => {
    let treeAreaData = state.treeAreaData
    let areaSelectedList = state.areaSelectedList
    let sourceDataList = treeAreaData[0]
    sourceDataList.checked = false
    sourceDataList.children.forEach(value => {
      value.checked = false
    })
    areaSelectedList.length !== 0 && areaSelectedList.forEach(value => {
      let index = _.findIndex(treeAreaData[0].children, item => { return item.code === value.code })
      if (index !== -1) { state.treeAreaData[0].children[index].checked = true }
    })
  },
  /* 提交后重置数据 */
  RESET_AREA_DATA: (state, data) => {
    state.areaSelectedList = []
    state.selectedAreaListStr = {}
    state.treeAreaData = []
  }
}

const actions = {
  getAreaTreeList ({ state, commit }, { payload: { data, cb } }) {
    let { url, type, params } = data
    return new Promise((resolve, reject) => {
      ApiRequest(url, type, params, true).then(res => {
        if (cb) { cb(res) }
        if (res.retStatus === '1') {
          commit('SET_AREA_TREE', res.retData)
        }
        resolve(res.retData)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
